package com.mj.express.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.SYY.cbsdk.ui.AppControl;
import com.dyk.hfsdk.dao.util.DevListener;
import com.dyk.hfsdk.ui.Access;
import com.mj.express.R;
import com.mj.express.adapter.CompanySpinnerAdapter;
import com.mj.express.bean.ExpressCompany;
import com.mj.express.bean.Kuaidi100JSON;
import com.mj.express.service.ExpressService;
import com.mj.express.util.NetUtils;
import com.mj.express.util.RegUtil;
import com.mj.express.zxing.CaptureActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 快递查询
 * 前期先列出常用的快递公司  TODO 后期通过欢迎界面放到数据库里 并加上条码扫描
 * @author zhaominglei
 * @date 2015-3-15
 * 
 */
public class MainActivity extends Activity implements OnClickListener,DevListener {
	@SuppressWarnings("unused")
	private static final String TAG = MainActivity.class.getSimpleName();
	public static final String MUMAYI_APPID = "c9c70108475fdb5bfvOaUen8Z4wqJ2fj/GKgIGqQ+tzP8SaYfS3UZHN2IYjpkQDMgg"; //app_id
	public static final String MUMAYI_APPCHANNEL = "木蚂蚁"; //app_channel
	private ExpressService expressService = new ExpressService();
	private boolean isExit = false;
	private TimerTask timerTask;
	private LinearLayout miniAdLinearLayout; //迷你广告
	private Spinner companySpinner; //快递公司
	private CompanySpinnerAdapter companySpinnerAdapter;
	private String companytype; //已选的快递公司
	private EditText expressnoText; //快递单号输入框
	private String expressno; //快递单号
	private ImageView tiaomaView; //条形码
	private Button queryBtn; //查询
	private ProgressBar queryProgressBar; //查询进度条
	private TextView resultView; //结果
	private Button appOffersButton; //推荐应用
	private String referer; //来自那个链接
	private String result; //条形码扫描结果
	@SuppressWarnings("unused")
	private String format; //条形码格式
	private String selectedCompanytype; //条形码扫描传递过来的 已选的快递公司
	private Access access;
	private AppControl appControl;
	
	@SuppressWarnings("serial")
	private List<ExpressCompany> expressCompanies = new ArrayList<ExpressCompany>(){
		{
			add(new ExpressCompany("yunda", "韵达快递"));
			add(new ExpressCompany("yuantong", "圆通速递"));
			add(new ExpressCompany("shentong", "申通速递"));
			add(new ExpressCompany("huitongkuaidi", "百世汇通"));
			add(new ExpressCompany("youzhengguonei", "邮政包裹"));
			add(new ExpressCompany("tiantian", "天天快递"));
			add(new ExpressCompany("zhongtong", "中通快递"));
			add(new ExpressCompany("shunfeng", "顺丰速递"));
			add(new ExpressCompany("ems", "EMS"));
			add(new ExpressCompany("zhaijisong", "宅急送"));
			add(new ExpressCompany("quanfengkuaidi", "全峰快递"));
		}
	};
	private ExpressCompany expressCompany; //快递公司
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		init();
	}
	
	private void init() {
		miniAdLinearLayout = (LinearLayout)findViewById(R.id.miniAdLinearLayout);
		companySpinner = (Spinner)findViewById(R.id.express_company_spinner);
		expressnoText = (EditText)findViewById(R.id.express_expressno_edt);
		tiaomaView = (ImageView)findViewById(R.id.express_tiaoma);
		queryBtn = (Button)findViewById(R.id.express_query_btn);
		queryProgressBar = (ProgressBar)findViewById(R.id.express_query_progressbar);
		resultView = (TextView)findViewById(R.id.express_result);
		appOffersButton = (Button)findViewById(R.id.appOffersButton);
		
		tiaomaView.setOnClickListener(this);
		queryBtn.setOnClickListener(this);
		appOffersButton.setOnClickListener(this);
		companySpinnerAdapter = new CompanySpinnerAdapter(this, expressCompanies);
		companySpinner.setAdapter(companySpinnerAdapter);
		
		referer = getIntent().getStringExtra("referer");
		result = (getIntent().getExtras() != null) ? getIntent().getExtras().getString("result") : "";
		format = (getIntent().getExtras() != null) ? getIntent().getExtras().getString("format") : "";
		selectedCompanytype = getIntent().getStringExtra("selectedCompanytype"); 
		if (referer != null && referer.equals("CaptureActivity")) {
			expressnoText.setText("");
			if (selectedCompanytype != null && !selectedCompanytype.equals("")) {
				int position = 0;
				for (int i = 0; i < expressCompanies.size(); i++) {
					ExpressCompany expressCompany = expressCompanies.get(i);
					if (expressCompany != null && selectedCompanytype.equals(expressCompany.getCode())) {
						position = i;
						break;
					}
				}
				companySpinner.setSelection(position, true);
			}
			if (result != null && !result.equals("")) {
				if (RegUtil.isNumber(result)) {
					expressnoText.setText(result);
				}
			}
		}
		
		appControl = AppControl.getInstance();
		appControl.init(MainActivity.this, MUMAYI_APPID, MUMAYI_APPCHANNEL);
		appControl.loadPopAd(MainActivity.this);
		appControl.showPopAd(MainActivity.this, 60 * 1000);
		appControl.showInter(MainActivity.this, miniAdLinearLayout);
		
		access = Access.getInstance();
		// 初始化带player_id
		access.init(MainActivity.this, MUMAYI_APPID, MUMAYI_APPCHANNEL);
		// 设置初始积分                                                              
		access.setdefaultSCORE(this, 100);
		// 设置获取积分的监听
		access.setAppListener(this, this);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.express_tiaoma:
			expressCompany = (ExpressCompany)companySpinner.getSelectedItem();
			companytype = expressCompany.getCode();
			Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
			intent.putExtra("referer", "MainActivity");
			intent.putExtra("selectedCompanytype", companytype);
			startActivity(intent);
			MainActivity.this.finish();
			break;
			
		case R.id.express_query_btn:
			resultView.setText("");
			expressno = expressnoText.getText().toString();
			if (expressno == null || expressno.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.express_expressno_hint, Toast.LENGTH_SHORT).show();
				return;
			}
			expressCompany = (ExpressCompany)companySpinner.getSelectedItem();
			companytype = expressCompany.getCode();
			if (companytype == null || companytype.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.express_error3, Toast.LENGTH_SHORT).show();
				return;
			}
			getExpressInfo();
			break;
		case R.id.appOffersButton:
			access.openWALL(MainActivity.this);
			break;

		default:
			break;
		}
	}
	
	private void getExpressInfo() {
		if (NetUtils.isConnected(getApplicationContext())) {
			queryProgressBar.setVisibility(View.VISIBLE);
			new ExpressInfoAsyncTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onBackPressed() {
		if (isExit) {
			MainActivity.this.finish();
		} else {
			isExit = true;
			Toast.makeText(MainActivity.this, R.string.exit_msg, Toast.LENGTH_SHORT).show();
			timerTask = new TimerTask() {
				@Override
				public void run() {
					isExit = false;
				}
			};
			new Timer().schedule(timerTask, 2*1000);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		appControl.close(this);
	}
	
	public class ExpressInfoAsyncTask extends AsyncTask<String, String, Kuaidi100JSON> {
		@Override
		protected Kuaidi100JSON doInBackground(String... params) {
			return expressService.getExpressInfo(companytype, expressno);
		}

		@Override
		protected void onPostExecute(Kuaidi100JSON result) {
			queryProgressBar.setVisibility(View.GONE);
			if (result != null) {
				String status = result.getStatus();
				if ("200".equals(status)) {
					StringBuilder sb = new StringBuilder();
					List<Kuaidi100JSON.KuaidiStage> data = result.getData();
					for (int i = 0; (data != null && data.size() > 0) && i < data.size(); i++) {
						Kuaidi100JSON.KuaidiStage kuaidiStage = data.get(i);
						sb.append(kuaidiStage.getFtime()).append("\n");
						sb.append("     ").append(kuaidiStage.getContext()).append("\n\n");
					}
					resultView.setText(sb.toString());
				} else {
					Toast.makeText(getApplicationContext(), R.string.express_error2, Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(getApplicationContext(), R.string.express_error2, Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	
	@Override
	public void onDevSucceed(int eggs) {
		System.out.println("积分获取成功:" + eggs);
	}

	@Override
	public void onDevFailed(String message) {
		System.out.println("积分获取失败:" + message);
	}

	@Override
	public void onClose(Context context) {
		((Activity) context).finish();
	}	
}
